﻿using LitJson;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace GameBoxTools
{
    public static class Common
    {
        public const string defaultOverdrawScene = "Assets/GameBoxTools/Scenes/StatisticOverDraw.unity";
        public const string defaultTransRateScene = "Assets/GameBoxTools/Scenes/StatisticTransparent.unity";

        /// <summary>
        /// 获取所选文件夹下对应扩展的物体
        /// </summary>
        /// <param name="ext">扩展名</param>
        /// <returns></returns>
        public static string[] GetItemsPathFromDir(string ext)
        {
            //得到的文件夹路径：eg-->D:\xxxxx\Assets\uiprefabs
            string _folderAssetPath = EditorUtility.OpenFolderPanel("选择搜索文件夹", "", "");
            if (string.IsNullOrEmpty(_folderAssetPath)) return null;


            //获取文件夹底下所有prefab文件路径
            var allPrePath = Directory.GetFiles(_folderAssetPath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(ext));

            return allPrePath.ToArray();
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="context">内容</param>
        public static void SaveToFile(string filename, JsonData context)
        {
            //Save Data
            string savePath = EditorUtility.SaveFilePanel("导出文件到", "", filename, "json");
            if (!string.IsNullOrEmpty(savePath)/* && !string.IsNullOrEmpty(context)*/)
            {
                FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs); // 创建写入流

                JsonWriter w = new JsonWriter();
                w.PrettyPrint = true;
                w.IndentValue = 4;
                JsonMapper.ToJson(context, w);

                sw.Write(w.ToString());
                sw.Close(); //关闭文件

                Debug.Log("[<color=#00ff00>导出成功</color>]");
            }
            else
            {
                Debug.Log("[<color=#ffff00>导出终止</color>]");
            }
        }

        /// <summary>
        /// 分析粒子性能
        /// </summary>
        /// <param name="isOverdraw">true:分析overdraw， false:分析透明占比</param>
        public static void AnalyzeParticleSystem(bool isOverdraw)
        {
            if(!(Selection.activeObject is GameObject))
            {
                Debug.LogError("请选中所需分析粒子的Prefab");
                return;
            }

            GameObject selectGo = Selection.activeObject as GameObject;
            if (selectGo == null)
            {
                Debug.LogError("请选中所需分析粒子的Prefab");
                return;
            }

            string openscene = defaultOverdrawScene;
            if (!isOverdraw)
                openscene = defaultTransRateScene;
			
			string oriscene = SceneManager.GetActiveScene().path;
            if (!SceneManager.GetActiveScene().Equals(openscene))
            {
                EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
                EditorSceneManager.OpenScene(openscene);
            }

            if (!SceneManager.GetActiveScene().Equals(openscene))
            {
                EditorSceneManager.OpenScene(openscene);
            }

            var PSRoot = GameObject.Find("PSRoot").transform;
			PSRoot.GetComponent<BaseStatistic>().orignScene = oriscene;

            //清理已有child结点
            var count = PSRoot.transform.childCount;
            while(count>0)
            {
                var child = PSRoot.transform.GetChild(0).gameObject;
                Object.DestroyImmediate(child);
                child = null;

                count = PSRoot.transform.childCount;
            }

            //添加当前粒子到PSRoot
            GameObject newGo = Object.Instantiate(selectGo);
            newGo.name = selectGo.name;
            newGo.transform.localPosition = Vector3.zero;
            newGo.transform.SetParent(PSRoot, false);

            EditorApplication.isPlaying = true;
        }

        //进度条
        public static void ShowProgress(int total, int cur)
        {
            float val = (float)cur / (float)total;
            EditorUtility.DisplayProgressBar("Searching", "please waiting...", val);
        }

        public static void CloseProgress()
        {
            EditorUtility.ClearProgressBar();
        }
    }
}